<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>打地鼠</title>
		<style>
			#container {
				margin: 0 auto;
				width: 320px;
				text-align: center;
			}
			
			img {
				width: 100px;
				height: 100px;
			}
		</style>
	</head>
	<body>
		<p id="countTime"></p>
		<div id="container">
			<img src="img/5.jpg" onclick="beat(this)"/>
			<img src="img/5.jpg" onclick="beat(this)"/>
			<img src="img/5.jpg" onclick="beat(this)"/>
			<img src="img/5.jpg" onclick="beat(this)"/>
			<img src="img/5.jpg" onclick="beat(this)"/>
			<img src="img/5.jpg" onclick="beat(this)"/>
			<img src="img/5.jpg" onclick="beat(this)"/>
			<img src="img/5.jpg" onclick="beat(this)"/>
			<img src="img/5.jpg" onclick="beat(this)"/>
		</div>
		
		
		<p id="score"></p>

	</body>
	
	<script>
		var container = document.getElementById("container");
		
		setInterval(function() {
			var rndShow = Math.random() * 9;
			
			// 向下取整
			var indexShow = Math.floor(rndShow);
					
			// 改变图片，变成老鼠
			container.children[indexShow].src = "img/2.png";
						
	
	
			var rndHide = Math.random() * 9;
			
			// 向下取整
			var indexHide = Math.floor(rndHide);
	
			// 变回草					
			container.children[indexHide].src = "img/5.jpg";
						
		}, 600);
		
		
		// 所有的图片
		var arr = container.children;
		
		/*
		for (var i in arr) {
			// 给每个图片绑定点击函数，当点击的时候进入这个函数
			arr[i].onclick = function() {
				console.log(this.src);
			}
		}
		*/
		
		var startFlag = 0;
		var score = 0;
		function beat(obj) {
			
			if (startFlag == 0) {
				countTime();
				startFlag = 1;
			}
			
			var str = obj.src;
			
			// str.charAt 拿到第几个字符串 str.length-5 倒数第五个
			var imgFlag = str.charAt(str.length-5);
			
			if (imgFlag == "2") {
				//str.length-5 倒数第五个字符串是地鼠的话 分数+1
				score++;
			}
			
			if (imgFlag == "5") {
				//str.length-5 倒数第五个字符串是草的话 分数-1
				score--;
			}
			
			//图片变草
			obj.src = "img/5.jpg";
			
			
			// 更新分数
			document.getElementById("score").innerHTML = "分数：" + score;
			
			
			// 挑战成功
			// 已经打了35个地鼠
			if (score > 35) {
				
				alert('挑战成功');
				
				startFlag = 0;
				count = 60;
				
				clearInterval(timer);
				
				
				// 显示倒计时时间
				document.getElementById("countTime").innerHTML = "";
				// 更新分数
				document.getElementById("score").innerHTML = "";
			}
			
		}
		
		var timer = null;
		var count = 60;
		
		function countTime() {
			
			// 倒计时定时器
			timer = setInterval(function() {
				if (count < 0) {
					alert('挑战失败');
					clearInterval(timer);
				}
				
				count--;
				
				// 显示倒计时时间
				document.getElementById("countTime").innerHTML = "倒计时：" + count + "秒";
			}, 1000);
		}
		
	</script>
</html>
